package net.vsame.sqlmanger;

import java.util.Map;

import net.vsame.sqlmanger.mysql.DataBase;
import net.vsame.sqlmanger.mysql.DataBaseManger;
import net.vsame.url2sql.domain.Url2SqlContext;
import net.vsame.url2sql.domain.Url2SqlModel;
import net.vsame.url2sql.domain.Url2SqlModelChain;
import net.vsame.url2sql.helper.WebHelper;
import net.vsame.url2sql.utils.JdbcUtils;

public class SqlMangerModel extends Url2SqlModel{

	private static String database;

	@Override
	public void init() {
		this.addUrlConfig("mysql/database", DataBase.class);
		this.addUrlConfig("mysql/databasemanger", DataBaseManger.class);
		
		System.out.println("init....");
	}

	@Override
	public boolean isWeb() {
		return false;
	}
	
	public static String getDatabase(){
		if(database == null){
			Map<String, Object> map = JdbcUtils.queryOne("select database() `database`");
			database = map.get("database")+"";
		}
		return database;
	}
	public void setDatabase(Url2SqlContext c, String database){
		try{
			JdbcUtils.execute("use " + database);
		}catch (Exception e) {
			c.putError(1, e.getMessage());
		}
	}

	@Override
	public void invoke(Url2SqlModelChain chain) {
		Url2SqlContext c = WebHelper.getContext();
		String use = c.getParam("use.database");
		if(use == null){
			setDatabase(c, getDatabase());
		}else{
			setDatabase(c, use);
		}
		Map<String, Object> map = JdbcUtils.queryOne("select database() `database`");
		System.out.println(map.get("database")+"");;
		super.invoke(chain);
	}

}
